<script setup lang="ts">
import { CirclePlus, Refresh, Download, RefreshRight, Search, Files } from "@element-plus/icons-vue"
import { onMounted, reactive, ref, watch } from "vue"
import {
  ElMessage,
  ElMessageBox,
  FormInstance,
  FormRules,
  genFileId,
  UploadInstance,
  UploadProps,
  UploadRawFile
} from "element-plus"
import { usePagination } from "@/hooks/usePagination"
import {
  AddProjectApi,
  DeleteProjectApi,
  ExportStatisticsExcelApi,
  FindProjectByCondApi,
  UpdateProjectApi
} from "@/api/project"
import {
  IAddProjectRequestData,
  IExportStatisticsExcelRequestData,
  IGetProjectResponseData,
  IUpdateRequestData
} from "@/api/project/types/project"
import { getAdminByNameDataApi } from "@/api/admin"
import { IGetAdminByNameData } from "@/api/admin/types/admin"
import { getDepartmentIdAndNameList } from "@/api/department"
import { IGetDepartmentData } from "@/api/department/types/department"
import { useUserStore } from "@/store/modules/user"
import { IUserInfoData } from "@/api/login/types/login"
import { hasAnthority, isExcel, openDownload, showPromptMessage } from "@/utils"
import { getExcelTemplateApi } from "@/api/project"
import Table from "./table.vue"
import { getToken } from "@/utils/cache/cookies"
const userStore = useUserStore()
const activeName = ref(0)
const userInfo = userStore.userInfo as IUserInfoData
const auth = userStore.auth
const loading = ref(false)
const searchProjectData = ref({
  name: "",
  year: "",
  adminName: undefined,
  departmentId: undefined
})
const searchFormRef = ref<FormInstance | null>(null)
/*#查  */
const {
  paginationData: projectPaginationData
  // handleCurrentChange: projectHandleCurrentChange,
  // handleSizeChange: projectHandleSizeChange
} = usePagination()

// 跳转页面
const projectHandleCurrentChange = (newPage: number) => {
  projectPaginationData.currentPage = newPage // 更新当前页面
  getProjectList(activeName.value)
}

// 更新PageSize
const projectHandleSizeChange = (newSize: number) => {
  projectPaginationData.pageSize = newSize // 更新页面大小
  getProjectList(activeName.value)
}

// #查 修改
const projectListData = ref<IGetProjectResponseData[]>([])
const currentUpdateId = ref<string | undefined>(undefined)
const handleUpdate = (row: IUpdateRequestData) => {
  currentUpdateId.value = row.id
  addFormData.adminName = row.adminName
  addFormData.departmentId = row.departmentId
  addFormData.note = row.note
  addFormData.name = row.name
  addFormData.year = row.year + ""
  addFormData.contactName = row.contactName
  addFormData.contactPhone = row.contactPhone
  addFormData.startDate = row.startDate
  addFormData.endDate = row.endDate
  addFormData.establishType = row.establishType
  addFormData.establishAddress = row.establishAddress
  addFormData.charge = row.charge
  addFormData.tuitionFee = row.tuitionFee
  addFormData.trainingNum = row.trainingNum
  addFormData.cooperation = row.cooperation
  addFormData.classHours = row.classHours
  addFormData.content = row.content
  addDialogVisible.value = true
}
const refreshing = ref(false)
const getProjectList = (active: number) => {
  loading.value = true
  if (refreshing.value) return
  refreshing.value = true
  FindProjectByCondApi(
    {
      page: projectPaginationData.currentPage,
      size: projectPaginationData.pageSize,
      name: searchProjectData.value.name,
      year: searchProjectData.value.year,
      adminName: searchProjectData.value.adminName,
      departmentId: searchProjectData.value.departmentId
    },
    active
  )
    .then((res) => {
      projectListData.value = res.data.list
      projectPaginationData.total = res.data.total
    })
    .catch(() => {
      projectListData.value = []
    })
    .finally(() => {
      refreshing.value = false
      loading.value = false
    })
}
// #查

// #增

const addFormRules: FormRules = reactive({
  name: [{ required: true, trigger: "blur", message: "请输入项目名称" }],
  year: [{ required: true, trigger: "blur", message: "请选择立项年度" }],
  adminName: [{ required: true, trigger: "blur", message: "请输入负责人" }],
  departmentId: [{ required: true, trigger: "blur", message: "请选择办学单位" }]
})
const addFormRef = ref<FormInstance | null>()
const inlineFormRef = ref<FormInstance | null>()
const addDialogVisible = ref(false)
const addFormData = reactive<IAddProjectRequestData>({
  name: "",
  year: "",
  adminName: undefined,
  departmentId: userInfo.departmentId,
  note: "",
  contactName: "",
  contactPhone: "",
  startDate: "",
  endDate: "",
  establishType: "独立办学",
  establishAddress: "",
  charge: "",
  tuitionFee: "",
  trainingNum: "",
  cooperation: "",
  classHours: "",
  content: ""
})

const handleSearch = () => {
  if (projectPaginationData.currentPage === 1) {
    getProjectList(activeName.value)
  } else {
    projectPaginationData.currentPage = 1
  }
}
const resetSearch = () => {
  if (projectPaginationData.currentPage === 1) {
    // searchProjectData.value={}
    inlineFormRef.value?.resetFields()
    searchFormRef.value?.resetFields()
    getProjectList(activeName.value)
  } else {
    projectPaginationData.currentPage = 1
  }
}

const resetForm = () => {
  currentUpdateId.value = undefined
  addFormRef.value?.resetFields()
}

const handleCreate = () => {
  addFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (currentUpdateId.value === undefined) {
        AddProjectApi(addFormData).then(() => {
          ElMessage.success("新增成功")
          addDialogVisible.value = false
          getProjectList(activeName.value)
        })
      } else {
        UpdateProjectApi({
          id: currentUpdateId.value,
          ...addFormData
        }).then(() => {
          ElMessage.success("修改成功")
          addDialogVisible.value = false
          getProjectList(activeName.value)
        })
      }
    } else {
      return false
    }
  })
}

const { paginationData: adminPaginationData } = usePagination()
const AdminData1 = ref<IGetAdminByNameData[]>([])
const DepartmentData = ref<IGetDepartmentData[]>([])

const getAdminDataList = (departmentId: undefined | number): Promise<IGetAdminByNameData[]> => {
  return new Promise((resolve, reject) => {
    loading.value = true
    getAdminByNameDataApi({
      name: "",
      departmentId
    })
      .then((res) => {
        resolve(res.data.users)
      })
      .catch((err) => {
        AdminData1.value = []
        reject(err)
      })
      .finally(() => {
        loading.value = false
      })
  })
}

watch([() => searchProjectData.value.departmentId], async (newV) => {
  const res = await getAdminDataList(newV[0])
  AdminData1.value = res
  searchProjectData.value.adminName = undefined
})
const getDepartmentDataList = () => {
  loading.value = true
  getDepartmentIdAndNameList({ name: "", departmentId: userInfo.departmentId })
    .then((res) => {
      DepartmentData.value = res.data.list
    })
    .catch(() => {
      DepartmentData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}

const handleRefresh = () => {
  getProjectList(activeName.value)
}
//#region 删
const handleDelete = (row: IUpdateRequestData) => {
  ElMessageBox.confirm(`正在删除项目：${row.name}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    DeleteProjectApi(row.id).then(() => {
      ElMessage.success("删除成功")
      getProjectList(activeName.value)
    })
  })
}
//#endregion

//#导出
const exportDialogVisible = ref(false)
const exportFormRef = ref<FormInstance | null>(null)
const exportFormData = ref<IExportStatisticsExcelRequestData>({
  departmentId: userInfo.departmentId === 0 ? undefined : userInfo.departmentId,
  year: "",
  startDate: "",
  endDate: ""
})
const handleConfirmExport = () => {
  loading.value = true
  ExportStatisticsExcelApi(exportFormData.value)
    .then((res) => {
      openDownload(res.blob, res.fileName)
      exportDialogVisible.value = false
    })
    .finally(() => {
      loading.value = false
    })
}

const getExcelTemplate = () => {
  getExcelTemplateApi().then((res) => {
    openDownload(res.blob, res.fileName)
  })
}

const uploadRef = ref<UploadInstance | null>(null)
const handleExceed: UploadProps["onExceed"] = (files) => {
  uploadRef.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  uploadRef.value!.handleStart(file)
}
const handleChange: UploadProps["onChange"] = async (uploadFile) => {
  if (isExcel(uploadFile.raw?.type)) {
    uploadRef.value?.submit()
  } else {
    showPromptMessage("error", "文件格式错误（请上传excel文件）")
  }
}
const handleSuccess: UploadProps["onSuccess"] = (response) => {
  if (response.code === 200) showPromptMessage("success", response.msg)
}
//#end
onMounted(async () => {
  const res = await getAdminDataList(userInfo.departmentId)
  AdminData1.value = res
  getDepartmentDataList()
}),
  watch(
    [
      () => adminPaginationData.currentPage,
      () => searchProjectData.value.adminName,
      () => searchProjectData.value.year,
      () => searchProjectData.value.departmentId
    ],
    () => {
      getProjectList(activeName.value)
    },
    { deep: true, immediate: true }
  )

const handleClick = (e: any) => {
  getProjectList(e.paneName)
}
</script>

<template>
  <div class="app-container" v-loading="loading" element-loading-text="加载中">
    <div>
      <el-card shadow="never" class="search-wrapper">
        <el-form ref="searchFormRef" :inline="true" :model="searchProjectData">
          <el-form-item prop="name" label="项目名称">
            <el-input v-model="searchProjectData.name" placeholder="请输入" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
            <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <el-card shadow="never" class="my-5">
        <el-form inline ref="inlineFormRef" :model="searchProjectData">
          <el-form-item v-if="userStore.auth === '2'" prop="departmentId" label="办学单位">
            <el-select filterable v-model="searchProjectData.departmentId" placeholder="选择办学单位">
              <el-option v-for="item in DepartmentData" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item prop="adminName" label="负责人">
            <el-input v-model="searchProjectData.adminName" placeholder="输入负责人" />
          </el-form-item>
          <el-form-item prop="year" label="立项年度">
            <el-date-picker
              v-model="searchProjectData.year"
              type="year"
              value-format="YYYY"
              placeholder="选择立项年度"
            />
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <el-card shadow="never">
      <div class="flex justify-between">
        <div class="flex">
          <el-button
            class="mr-3"
            v-if="hasAnthority('project.add')"
            type="primary"
            :icon="CirclePlus"
            @click="addDialogVisible = true"
            >新增项目</el-button
          >
          <el-upload
            v-if="hasAnthority('project.add')"
            ref="uploadRef"
            class="mr-3"
            :auto-upload="false"
            :limit="1"
            :on-exceed="handleExceed"
            action="/api/v2/project/importProject"
            :show-file-list="false"
            accept=".xlsx,.xls"
            method="post"
            :on-change="handleChange"
            :on-success="handleSuccess"
            :headers="{ token: getToken() }"
          >
            <el-button type="warning" :icon="Files">导入办学信息</el-button>
          </el-upload>

          <el-button :icon="Download" color="#3c6382" @click="getExcelTemplate">获取批量导入模板</el-button>

          <el-button
            v-if="hasAnthority('project.excel')"
            @click="exportDialogVisible = true"
            type="success"
            color="#2980b9"
            :icon="Download"
            >导出办学信息</el-button
          >
        </div>
        <div>
          <el-tooltip content="刷新表格">
            <el-button type="primary" :icon="RefreshRight" circle @click="handleRefresh" />
          </el-tooltip>
        </div>
      </div>
      <div class="mt-5">
        <el-tabs v-model="activeName" type="border-card" class="demo-tabs" @tab-click="handleClick">
          <el-tab-pane label="全部" :name="0">
            <Table :data="projectListData" @update="handleUpdate" @delete="handleDelete" />
          </el-tab-pane>
          <el-tab-pane label="办学信息缺失" :name="1"
            ><Table :data="projectListData" @update="handleUpdate" @delete="handleDelete"
          /></el-tab-pane>
          <el-tab-pane label="未上传必要资料" :name="2"
            ><Table :data="projectListData" @update="handleUpdate" @delete="handleDelete"
          /></el-tab-pane>
        </el-tabs>
      </div>
      <div class="mt-5">
        <el-pagination
          background
          :layout="projectPaginationData.layout"
          :page-sizes="projectPaginationData.pageSizes"
          :total="projectPaginationData.total"
          :page-size="projectPaginationData.pageSize"
          :currentPage="projectPaginationData.currentPage"
          @size-change="projectHandleSizeChange"
          @current-change="projectHandleCurrentChange"
        />
      </div>
    </el-card>

    <!--   新增/修改-->
    <el-dialog
      v-model="addDialogVisible"
      :title="currentUpdateId === undefined ? '新增项目' : '修改项目'"
      @close="resetForm"
      width="50%"
    >
      <div class="addform px-2">
        <el-form ref="addFormRef" :model="addFormData" :rules="addFormRules" label-width="140px" label-position="left">
          <el-form-item prop="name" label="项目名称">
            <el-input v-model="addFormData.name" placeholder="请输入" />
          </el-form-item>
          <el-form-item v-if="userInfo.authority === '2'" prop="departmentId" label="办学单位">
            <el-select filterable v-model="addFormData.departmentId" placeholder="选择办学单位">
              <el-option v-for="item in DepartmentData" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item prop="year" label="立项年度">
            <el-date-picker
              format="YYYY"
              value-format="YYYY"
              v-model="addFormData.year"
              type="year"
              placeholder="选择立项年度"
            />
          </el-form-item>
          <el-form-item prop="adminName" label="负责人">
            <el-input v-model="addFormData.adminName" placeholder="请输入负责人" />
          </el-form-item>
          <el-form-item prop="contactName" label="项目联系人姓名">
            <el-input v-model="addFormData.contactName" placeholder="请输入" />
          </el-form-item>
          <el-form-item prop="contactPhone" label="项目联系人电话">
            <el-input v-model="addFormData.contactPhone" placeholder="请输入" />
          </el-form-item>
          <el-form-item prop="startDate" label="开始时间">
            <el-date-picker
              value-format="YYYY-MM-DD"
              v-model="addFormData.startDate"
              type="date"
              placeholder="选择开始时间"
            />
          </el-form-item>
          <el-form-item prop="endDate" label="结束时间">
            <el-date-picker
              value-format="YYYY-MM-DD"
              v-model="addFormData.endDate"
              type="date"
              placeholder="选择结束时间"
            />
          </el-form-item>
          <el-form-item prop="establishType" label="办学方式">
            <el-radio-group v-model="addFormData.establishType">
              <el-radio label="独立办学">独立办学</el-radio>
              <el-radio label="合作办学">合作办学</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="establishAddress" label="办学地点">
            <el-input v-model="addFormData.establishAddress" placeholder="请输入,网络培训请填写平台网址" />
          </el-form-item>
          <el-form-item prop="charge" label="收费标准(元/人/天)">
            <el-input v-model="addFormData.charge" placeholder="请输入" />
          </el-form-item>
          <el-form-item prop="tuitionFee" label="学费总额(万元)">
            <el-input v-model="addFormData.tuitionFee" placeholder="请输入" />
          </el-form-item>
          <el-form-item prop="trainingNum" label="培训人数">
            <el-input v-model="addFormData.trainingNum" placeholder="请输入" />
          </el-form-item>
          <el-form-item prop="cooperation" label="合作方名称">
            <el-input v-model="addFormData.cooperation" placeholder="请输入,没有则填写无" />
          </el-form-item>
          <!-- <el-form-item prop="classHours" label="总课时数">
            <el-input type="number" v-model="addFormData.classHours" placeholder="请输入" />
          </el-form-item>
          <el-form-item prop="content" label="培训主要内容">
            <el-input v-model="addFormData.content" placeholder="请输入" />
          </el-form-item> -->
          <el-form-item prop="note" label="备注">
            <el-input v-model="addFormData.note" placeholder="请输入" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>

    <!-- 导出办学信息 -->
    <el-dialog v-model="exportDialogVisible" title="导出办学信息" @closed="exportFormRef?.resetFields()" width="50%">
      <div class="px-2">
        <el-form ref="exportFormRef" :model="exportFormData" label-width="140px" label-position="left">
          <el-form-item v-if="auth === '2'" prop="departmentId" label="办学单位">
            <el-select filterable v-model="exportFormData.departmentId" placeholder="选择办学单位">
              <el-option v-for="item in DepartmentData" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item prop="year" label="立项年度">
            <el-date-picker
              format="YYYY"
              value-format="YYYY"
              v-model="exportFormData.year"
              type="year"
              placeholder="选择立项年度"
            />
          </el-form-item>
          <el-form-item prop="startDate" label="开始时间">
            <el-date-picker
              value-format="YYYY-MM-DD"
              v-model="exportFormData.startDate"
              type="date"
              placeholder="选择开始时间"
            />
          </el-form-item>
          <el-form-item prop="endDate" label="结束时间">
            <el-date-picker
              value-format="YYYY-MM-DD"
              v-model="exportFormData.endDate"
              type="date"
              placeholder="选择结束时间"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="exportDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmExport">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.addform {
  max-height: 500px;
  overflow-y: auto;
}
.addform::-webkit-scrollbar {
  width: 6px;
  background-color: transparent;
}
.addform::-webkit-scrollbar-thumb {
  background-color: rgba(221, 221, 221, 0.5);
  border-radius: 4px;
}
</style>
